package com.mm.cloth.adapter;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.mm.cloth.R;
import com.mm.cloth.model.Category;

import java.util.List;

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {

    private List<Category> categoryList;
    private Context context;
    private OnCategoryClickListener listener;
    private OnCategoryLongClickListener longClickListener;
    private OnDeleteClickListener deleteClickListener;
    private OnExitEditModeListener exitEditModeListener;
    private OnCategoryDoubleClickListener doubleClickListener;
    private int selectedPosition = 0; // 默认选中第一个
    private int selectedCategoryId = 0; // 当前选中的分类ID
    private boolean isEditMode = false; // 是否处于编辑模式

    public CategoryAdapter(Context context, List<Category> categoryList) {
        this.context = context;
        this.categoryList = categoryList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_category, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Category category = categoryList.get(position);
        holder.tvCategory.setText(category.getName());
        
        // 设置选中状态
        boolean isSelected = position == selectedPosition;

        // 使用状态选择器，让背景自动根据选中状态变化
        holder.tvCategory.setSelected(isSelected);

        // 设置文字颜色和阴影效果
        if (isSelected) {
            holder.tvCategory.setTextColor(Color.parseColor("#8B4513")); // 选中时深棕色文字，与奶油粉色背景搭配
            holder.tvCategory.setShadowLayer(1.5f, 0.5f, 0.5f, Color.parseColor("#DDA0DD")); // 浅粉色阴影
        } else {
            holder.tvCategory.setTextColor(Color.parseColor("#87CEEB")); // 正常状态奶油蓝色
            holder.tvCategory.setShadowLayer(1.0f, 0.5f, 0.5f, Color.parseColor("#B0E0E6")); // 轻微蓝色阴影
        }
        
        // 设置删除按钮和编辑按钮的可见性
        // 全部分类不可删除和编辑
        if (isEditMode && position != 0) {
            holder.deleteBtn.setVisibility(View.VISIBLE);
            holder.editBtn.setVisibility(View.VISIBLE);
        } else {
            holder.deleteBtn.setVisibility(View.GONE);
            holder.editBtn.setVisibility(View.GONE);
        }
        
        // 简化的点击事件处理
        holder.tvCategory.setOnClickListener(v -> {
            if (!isEditMode) {
                int previousSelected = selectedPosition;
                selectedPosition = holder.getAdapterPosition();
                selectedCategoryId = category.getId();

                // 更新之前选中和当前选中的项
                notifyItemChanged(previousSelected);
                notifyItemChanged(selectedPosition);

                // 触发点击事件
                if (listener != null) {
                    listener.onCategoryClick(category);
                }
            } else {
                // 编辑模式下点击分类项退出编辑模式
                if (exitEditModeListener != null) {
                    exitEditModeListener.onExitEditMode();
                }
            }
        });

        // 长按事件 - 进入编辑模式
        holder.tvCategory.setOnLongClickListener(v -> {
            if (longClickListener != null && !isEditMode && holder.getAdapterPosition() > 0) {
                return longClickListener.onCategoryLongClick(category, holder.getAdapterPosition());
            }
            return false;
        });
        
        // 删除按钮点击事件
        holder.deleteBtn.setOnClickListener(v -> {
            int adapterPosition = holder.getAdapterPosition();
            if (adapterPosition != RecyclerView.NO_POSITION && deleteClickListener != null) {
                deleteClickListener.onDeleteClick(category, adapterPosition);
            }
        });

        // 编辑按钮点击事件
        holder.editBtn.setOnClickListener(v -> {
            int adapterPosition = holder.getAdapterPosition();
            if (adapterPosition != RecyclerView.NO_POSITION && doubleClickListener != null) {
                doubleClickListener.onCategoryDoubleClick(category, adapterPosition);
            }
        });
    }

    @Override
    public int getItemCount() {
        int count = categoryList == null ? 0 : categoryList.size();
        Log.d("CategoryAdapter", "getItemCount: " + count);
        return count;
    }

    /**
     * 刷新数据并记录日志
     */
    public void refreshData() {
        Log.d("CategoryAdapter", "refreshData called, 当前数据量: " + (categoryList == null ? 0 : categoryList.size()));
        notifyDataSetChanged();
    }



    public void setCategories(List<Category> categories) {
        Log.d("CategoryAdapter", "setCategories called, 新数据量: " + (categories == null ? 0 : categories.size()));

        this.categoryList = categories;

        if (categories != null) {
            for (int i = 0; i < categories.size(); i++) {
                Category cat = categories.get(i);
                Log.d("CategoryAdapter", "设置分类[" + i + "]: " + cat.getName() + " (ID: " + cat.getId() + ")");
            }
        }

        notifyDataSetChanged();
        Log.d("CategoryAdapter", "setCategories完成，getItemCount: " + getItemCount());
    }

    public void setOnCategoryClickListener(OnCategoryClickListener listener) {
        this.listener = listener;
    }
    
    public void setOnCategoryLongClickListener(OnCategoryLongClickListener listener) {
        this.longClickListener = listener;
    }
    
    public void setOnDeleteClickListener(OnDeleteClickListener listener) {
        this.deleteClickListener = listener;
    }

    public void setOnExitEditModeListener(OnExitEditModeListener listener) {
        this.exitEditModeListener = listener;
    }

    public void setOnCategoryDoubleClickListener(OnCategoryDoubleClickListener listener) {
        this.doubleClickListener = listener;
    }
    
    /**
     * 获取当前选中的位置
     * @return 选中的位置索引
     */
    public int getSelectedPosition() {
        return selectedPosition;
    }
    
    /**
     * 设置选中的位置
     * @param position 要选中的位置索引
     */
    public void setSelectedPosition(int position) {
        if (position >= 0 && position < getItemCount()) {
            int previousSelected = selectedPosition;
            selectedPosition = position;

            // 更新选中的分类ID
            if (position < categoryList.size()) {
                selectedCategoryId = categoryList.get(position).getId();
            }

            notifyItemChanged(previousSelected);
            notifyItemChanged(selectedPosition);
        }
    }

    /**
     * 获取当前选中的分类ID
     * @return 选中的分类ID
     */
    public int getSelectedCategoryId() {
        return selectedCategoryId;
    }

    /**
     * 设置选中的分类ID
     * @param categoryId 要选中的分类ID
     */
    public void setSelectedCategoryId(int categoryId) {
        this.selectedCategoryId = categoryId;
    }
    
    /**
     * 设置编辑模式
     * @param editMode 是否编辑模式
     */
    public void setEditMode(boolean editMode) {
        Log.d("CategoryAdapter", "setEditMode: " + editMode + ", 当前数据量: " + (categoryList == null ? 0 : categoryList.size()));

        if (this.isEditMode != editMode) {
            this.isEditMode = editMode;
            notifyDataSetChanged();

            // 打印编辑模式下的所有分类
            if (editMode && categoryList != null) {
                for (int i = 0; i < categoryList.size(); i++) {
                    Category cat = categoryList.get(i);
                    Log.d("CategoryAdapter", "编辑模式分类[" + i + "]: " + cat.getName() + " (ID: " + cat.getId() + ")");
                }
            }
        }
    }
    
    /**
     * 获取当前是否为编辑模式
     * @return 是否编辑模式
     */
    public boolean isEditMode() {
        return isEditMode;
    }
    
    /**
     * 设置选中的分类ID
     * @param categoryId 要选中的分类ID
     */
    public void setSelectedCategory(int categoryId) {
        if (this.selectedCategoryId != categoryId) {
            this.selectedCategoryId = categoryId;
            
            // 更新选中的位置
            int newSelectedPosition = -1;
            for (int i = 0; i < categoryList.size(); i++) {
                if (categoryList.get(i).getId() == categoryId) {
                    newSelectedPosition = i;
                    break;
                }
            }
            
            if (newSelectedPosition >= 0) {
                int previousSelected = selectedPosition;
                selectedPosition = newSelectedPosition;
                notifyItemChanged(previousSelected);
                notifyItemChanged(selectedPosition);
            }
        }
    }
    
    /**
     * 移除指定位置的分类
     * @param position 要移除的位置
     */
    public void removeCategory(int position) {
        if (position > 0 && position < categoryList.size()) {
            categoryList.remove(position);
            notifyItemRemoved(position);
            
            // 如果删除的是当前选中的项，则选中第一项
            if (selectedPosition == position) {
                selectedPosition = 0;
                notifyItemChanged(selectedPosition);
            } 
            // 如果删除的项在当前选中项之前，需要调整选中位置
            else if (selectedPosition > position) {
                selectedPosition--;
                notifyItemChanged(selectedPosition);
            }
        }
    }

    /**
     * 添加新分类
     * @param category 要添加的分类
     */
    public void addCategory(Category category) {
        if (categoryList != null) {
            categoryList.add(category);
            notifyItemInserted(categoryList.size() - 1);
        }
    }
    
    /**
     * 分类点击监听器
     */
    public interface OnCategoryClickListener {
        void onCategoryClick(Category category);
    }
    
    /**
     * 分类长按监听器
     */
    public interface OnCategoryLongClickListener {
        boolean onCategoryLongClick(Category category, int position);
    }
    
    /**
     * 删除按钮点击监听器
     */
    public interface OnDeleteClickListener {
        void onDeleteClick(Category category, int position);
    }

    /**
     * 退出编辑模式监听器
     */
    public interface OnExitEditModeListener {
        void onExitEditMode();
    }

    /**
     * 分类双击监听器
     */
    public interface OnCategoryDoubleClickListener {
        void onCategoryDoubleClick(Category category, int position);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvCategory;
        TextView deleteBtn;
        TextView editBtn;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvCategory = itemView.findViewById(R.id.tvCategory);
            deleteBtn = itemView.findViewById(R.id.deleteBtn);
            editBtn = itemView.findViewById(R.id.editBtn);
        }
    }
}